local Window = @@ui(window)
local Button = @@ui(button)
local Label = @@ui(label)
local UL = @@lib(love-ui-list)

local Signal = @@lib(hump.signal)

return Class {
   _name = "Gui",

   center = function (self, w, h)
      return $LG.getWidth()/2-w/2, $LG.getHeight()/2-h/2, w, h
   end,

   bottom_right = function (self, w, h)
      return $LG.getWidth() - (w+50), $LG.getHeight() - (h+50)
   end,

   init = function (self)
      self.config = pl.config.read 'ui/config'
      local hex2rgb = _src("colors").hex2rgb
      self.colors = pl.tablex.map(function (v) return {hex2rgb (v)} end, self.config)
      self.elements = {}
   end,

   reset = function (self)
      self.elements = {}
   end,
   
   update = function (self, dt)
      pl.tablex.foreach(self.elements, function (e)
			   if e.update then e:update(dt) end
			   if e.hoveritem > 0 then
			      Game.cursor.is_hovering = true
			   end
      end)
   end,
   
   draw = function (self)
      pl.tablex.foreach(self.elements, function (e)
			   if e.draw then e:draw() end
      end)
   end,
   
   window = function (self, ...)
      local w = Window(...)
      table.insert(self.elements, w)
      return w
   end,
   
   button = function (self, x, y, label, callback)
      local b = self:ul(x, y, 120, 35, label)
      b.onclick = function (i, b) callback(i, b) end
      table.insert(self.elements, b)
      return b
   end,
   
   label = function (self, ...)
      local l = Label(...)
      table.insert(self.elements, l)
      return l
   end,
   
   ul = function (self, x, y, w, h, ...) 
      -- taken from https://github.com/love2d-community/LOVE-Example-Browser
      -- add items yourself with u:add(a, b, c), then u:done() when finished
      local u = UL:new(x, y, w, h)
      @@VARARG_EACH(u:add(v))
      u:done()
      table.insert(self.elements, u)
      return u
   end,

   make_menu = function (x, y, ...)
      local is_even = function (n) return F("(%s %% 2 == 0)", n) end
      @@NEW_TABLE(items, callbacks)
      @@VARARG_EACH(
	 if is_even(i) then
	    @@ASSERT(type(v)=="string")
	 else
	    @@ASSERT(type(v)=="function")
		   end)
   end,

   mousepressed = function (self, x, y, b)
      lume.each(self.elements, function (e)
		   if e.mousepressed then e:mousepressed(x, y, b) end
      end)
   end,
   
   mousereleased = function (self, x, y, b)
      lume.each(self.elements, function (e)
		   if e.mousereleased then e:mousereleased(x, y, b) end
      end)
   end,
   
   mousemoved = function (self, x, y)
      lume.each(self.elements, function (e)
		   if e.mousemoved then e:mousemoved(x, y) end
      end)
   end,
   
   wheelmoved = function (self, x, y)
      lume.each(self.elements, function (e)
		   if e.wheelmoved then e:wheelmoved(x, y) end
      end)
   end,

}
